<?php

class ImageController extends GenesisController {

    public function imageRemoveAction() {
        $imageid=$this->_request->getParam('imageid');
        if (!is_numeric($imageid)) {
            $this->view->jsonMessage=json_encode(array('success'=>0,'message'=>'Invalid Image ID'));
            return;
        }
        $image = new Default_Model_Images();
        $image->find($imageid);
        if (!$image->getId()) {
            $this->view->jsonMessage=json_encode(array('success'=>0,'message'=>'Image not found in DB'));
            return;
        }
        $imageGroup = new Default_Model_ImageGroups();
        $imageGroup->find($image->getGroupId());
        if (!$imageGroup->getId()) {
            $this->view->jsonMessage=json_encode(array('success'=>0,'message'=>'Image Group ID not found!'));
            return;
        }
        $file=$this->_config->images->path.DIRECTORY_SEPARATOR.$imageGroup->getPath().DIRECTORY_SEPARATOR.$image->getFilename();
        $image->deleteRowByPrimaryKey();
        if (!is_file($file)) {
            $this->view->jsonMessage=json_encode(array('success'=>0,'message'=>'Row deleted, but picture could not be found!'));
            return;
        }
        if (!unlink($file)) {
            $this->view->jsonMessage=json_encode(array('success'=>0,'message'=>'Row deleted, but file could not be deleted!'));
            return;

        }
        $this->view->jsonMessage=json_encode(array('success'=>1,'message'=>'done'));
       
    }

    public function imageUploadAction() {

        $this->_helper->layout()->disableLayout();
        $fileName=$_FILES['imagefile']['name'];
        $tmpName=$_FILES['imagefile']['tmp_name'];
        $error=$_FILES['imagefile']['error'];
        $groupid=$this->_request->getParam('groupid');
                
        if ($error != 0) {
            $this->view->jsonMessage=json_encode(array('success'=>0,'message'=>'Upload Failed!'));
            return;
        }
        if (!is_numeric($groupid)) {
            $this->view->jsonMessage=json_encode(array('success'=>0,'message'=>'Group ID is not vaild!'));
            return;
        }
        $imageGroups = new Default_Model_ImageGroups();
        $imageGroups->find($groupid);
        if (!$imageGroups->getId()) {
            $this->view->jsonMessage=json_encode(array('success'=>0,'message'=>'Group ID not found!'));
            return;
        }
        
        $groupDirName=$this->_config->images->path.DIRECTORY_SEPARATOR.$imageGroups->getPath();

        if (!is_dir($groupDirName) && !mkdir($groupDirName)) {
            $this->view->jsonMessage=json_encode(array('success'=>0,'message'=>'cannot create group directory!'));
            return;
        }

        $fileToSave=$groupDirName.DIRECTORY_SEPARATOR.$fileName;

        if (!is_uploaded_file($tmpName)) {
            $this->view->jsonMessage=json_encode(array('success'=>0,'message'=>"Broken upload! please try again."));
            return;
        }

        if (!move_uploaded_file($tmpName,$fileToSave)) {
            $this->view->jsonMessage=json_encode(array('success'=>0,'message'=>"could not move picture file to gallery!"));
            return;
        }
        $image = new Default_Model_Images();
        $image->setGroupId($groupid);
        $image->setFilename($fileName);
        $image->save();
        if (!$image->getId()) {
            $this->view->jsonMessage=json_encode(array('success'=>0,'message'=>'could not add file to db!'));
            unlink($fileName);
            return;
        }

        $this->view->jsonMessage=json_encode(array('succcess'=>1,'message'=>'done'));
    }

    public function manageGalleriesAction() {

        $this->view->headLink()->appendStylesheet('/js/jqGrid/themes/ui.jqgrid.css');
        $this->view->headScript()->appendFile('/js/jqGrid/js/i18n/grid.locale-en.js');
        $this->view->headScript()->appendFile('/js/jqGrid/js/jquery.jqGrid.js');
        
    }

    public function showGalleryTableGridAction() {
        $this->view->headScript()->appendFile('/js/jquery/ajaxupload.js');
        $this->view->headLink()->appendStylesheet('/js/jqGrid/themes/ui.jqgrid.css');
        $this->view->headScript()->appendFile('/js/jqGrid/js/i18n/grid.locale-en.js');
        $this->view->headScript()->appendFile('/js/jqGrid/js/jquery.jqGrid.js');
        $id = $this->_request->getParam('groupid');

        $imageGroups = new Default_Model_ImageGroups();
        $imageGroups->find($id);

        $this->view->galleryLocation=$this->_config->images->path.DIRECTORY_SEPARATOR.$imageGroups->getPath().DIRECTORY_SEPARATOR;

        $this->view->groupId=$id;
        $this->view->groupTitle=$imageGroups->getTitle();
    }

    public function setImageTableJsonAction() {
       $id=$this->_request->getParam('id');
       $oper = $this->_request->getParam('oper');

       $groupId = $this->_request->getParam('groupid');
       
       $imageModel = new Default_Model_Images();
       $primaryKey = $imageModel->getMapper()->getDbTable()->getPrimaryKeyName();

       
       if (in_array($oper,array('edit','del')))
           $imageModel->find($id);
       if ($oper == 'del' ) {
           $imageModel->deleteRowByPrimaryKey();
       } else {

       unset($_POST['oper']);

       foreach ($_POST as $key=>$value) {
           if ($key == 'id')
               continue;
           $parseKey='set'.$imageModel->columnName2Var($key);
           $imageModel->$parseKey($value);
       }
       $imageModel->setGroupId($groupId);
       $imageModel->save();
       }

    }

    public function getImageTableJsonAction() {
        $page = $this->_request->getParam('page'); // get the requested page
        $limit = $this->_request->getParam('rows'); // get how many rows we want to have into the grid
        $sidx = $this->_request->getParam('sidx'); // get index row - i.e. user click to sort
        $sord = $this->_request->getParam('sord'); // get the direction if(!$sidx) $sidx =1;
        $groupId = $this->_request->getParam('groupid');

       $imageModel = new Default_Model_Images();
       $records = $imageModel->countRowsByGroupId($groupId);

        $total=ceil(($records)/$limit);
        if ($page > $total)
                $page=$total;


    $rows=array();
    if ($records>0) $rows=$imageModel->fetchListToArray('group_id = '.$groupId, $sidx.' '.$sord, $limit, ($page-1)*$limit);
       $primaryKey=$imageModel->getMapper()->getDbTable()->getPrimaryKeyName();


       //TODO: currently the first row has to be the primary key.
       $resultRows=array();
       foreach ($rows as $row) {
           $data=array();
           unset($row['group_id']);
           foreach ($row as $value) {
               $data[]=$value;
           }
           $resultRows[]=array(
                'id'=>$row[$primaryKey],
                'cell' => $data
               );

       }

       $ret = array(
            'page'=>$page,
            'total'=>$total,
            'records'=>$records,
            'rows'=>$resultRows);
        $this->view->jsonMessage=json_encode($ret);



    }

    public function setImageGroupsTableJsonAction() {
       $id=$this->_request->getParam('id');
       $oper = $this->_request->getParam('oper');

       $imageGroupModel = new Default_Model_ImageGroups();
       $primaryKey = $imageGroupModel->getMapper()->getDbTable()->getPrimaryKeyName();

       if (in_array($oper,array('edit','del')))
           $imageGroupModel->find($id);
       if ($oper == 'del' ) {
           $imageGroupModel->deleteRowByPrimaryKey();
       } else {

       unset($_POST['oper']);

       foreach ($_POST as $key=>$value) {
           if ($key == 'id')
               continue;
           $parseKey='set'.$imageGroupModel->columnName2Var($key);
           $imageGroupModel->$parseKey($value);
       }
       $imageGroupModel->save();
       }

    }

    public function getImageGroupsTableJsonAction() {
        $page = $this->_request->getParam('page'); // get the requested page
        $limit = $this->_request->getParam('rows'); // get how many rows we want to have into the grid
        $sidx = $this->_request->getParam('sidx'); // get index row - i.e. user click to sort
        $sord = $this->_request->getParam('sord'); // get the direction if(!$sidx) $sidx =1;

       $imageGroupModel = new Default_Model_ImageGroups();
       $records = $imageGroupModel->countAllRows();

        $total=ceil(($records)/$limit);
        if ($page > $total)
                $page=$total;


    $rows=array();
    if ($records>0) $rows=$imageGroupModel->fetchListToArray(null, $sidx.' '.$sord, $limit, ($page-1)*$limit);
       $primaryKey=$imageGroupModel->getMapper()->getDbTable()->getPrimaryKeyName();


       //TODO: currently the first row has to be the primary key.
       $resultRows=array();
       foreach ($rows as $row) {
           $data=array();
           foreach ($row as $value) {
               $data[]=$value;
           }
           $resultRows[]=array(
                'id'=>$row[$primaryKey],
                'cell' => $data
               );

       }

       $ret = array(
            'page'=>$page,
            'total'=>$total,
            'records'=>$records,
            'rows'=>$resultRows);
        $this->view->jsonMessage=json_encode($ret);


        
    }

}